import { login, getUserInfo, getDetail } from '@/api/user'
import { resetRouter } from '@/router'
const state = {
  token: localStorage.getItem('token') || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    state.token = data
    localStorage.setItem('token', data)
  },
  setUserInfo(state, data) {
    state.userInfo = { ...data }
  },
  removeToken(state) {
    state.token = ''
    localStorage.removeItem('token')
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await login(data)
    // store.commit('setToken', res.data.data)
    localStorage.setItem('loginTime', Date.now())
    store.commit('setToken', res)
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    const detail = await getDetail(res.userId)
    // console.log(23, res)
    store.commit('setUserInfo', {
      ...res,
      ...detail
    })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
